/*
{
  car001: {name:'本田',price:100},
  car002: {name:'宝马',price:200},
  car003: {name: '奔驰',price:240}
}
 */

import { createContext, useContext, useState, memo } from 'react'

const CarsContext = createContext()

const Car = ({ id, car, incr, decr }) => {
  console.log(id)
  return (
    <div>
      <p>名称:{car.name}</p>
      <p>价格: {car.price}</p>
      <button className="btn btn-primary" onClick={() => incr(id)}>
        增加
      </button>
      <button className="btn btn-primary" onClick={() => decr(id)}>
        减少
      </button>
    </div>
  )
}
const Cars = () => {
  console.log('Cars')
  // return <CarsContext.Consumer>{({ cars, incr, decr }) => Object.keys(cars).map((id) => <Car id={id} key={id} car={cars[id]} incr={incr} decr={decr} />)}</CarsContext.Consumer>
  const { cars, incr, decr } = useContext(CarsContext)
  return (
    <div>
      {Object.keys(cars).map((id) => (
        <Car id={id} key={id} car={cars[id]} incr={incr} decr={decr} />
      ))}
    </div>
  )
}

const ProductList = memo(() => {
  console.log('ProductList')
  return (
    <>
      <h3>汽车:</h3>
      <Cars />
    </>
  )
})

const CarsDemo = () => {
  console.log('carsDemo')
  const [state, setState] = useState({
    car001: { name: '本田', price: 100 },
    car002: { name: '宝马', price: 200 },
    car003: { name: '奔驰', price: 240 },
  })
  const incrPrice = (carId) => {
    setState({
      ...state,
      [carId]: {
        ...state[carId],
        price: state[carId].price + 1,
      },
    })
  }
  const decrPrice = (carId) => {
    setState({
      ...state,
      [carId]: {
        ...state[carId],
        price: state[carId].price - 1,
      },
    })
  }
  return (
    <CarsContext.Provider
      value={{
        cars: state,
        incr: incrPrice,
        decr: decrPrice,
      }}
    >
      <h2>产品展厅</h2>
      <ProductList />
    </CarsContext.Provider>
  )
}

export default CarsDemo
